package com.Policing.Polling;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;


import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.JavaBean.OffSaveAbnormal;
import com.Policing.JavaBean.OffSaveSiteDate;
import com.Policing.LogUtils;
import com.Policing.Okhttps.HttpOkHttp;
import com.Policing.Okhttps.MyOkHttp;
import com.Policing.R;
import com.Policing.Repairs.CmlRequestBody;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.Since_case.Since_case;
import com.Policing.util.ThreadPool;
import com.Policing.util.VibrateUtil;
import com.Policing.util.VibrateUtils;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.gg.reader.api.dal.GClient;
import com.gg.reader.api.protocol.gx.EnumG;
import com.gg.reader.api.protocol.gx.Message;
import com.gg.reader.api.protocol.gx.MsgBaseInventoryEpc;
import com.gg.reader.api.protocol.gx.MsgBaseSetBaseband;
import com.gg.reader.api.protocol.gx.MsgBaseSetPower;
import com.gg.reader.api.protocol.gx.MsgBaseStop;
import com.gg.reader.api.protocol.gx.ParamEpcReadTid;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.seuic.uhf.EPC;
import com.seuic.uhf.UHFService;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import sakura.bottommenulibrary.bottompopfragmentmenu.BottomMenuFragment;


public class Site_Activity extends BaseActivity implements OnDismissListener, AMapLocationListener {

    public static final String TAG = "Hua===";
    private String completed;

    //    Button rfid;
    UHFService mDevice = UHFService.getInstance();
    List<EPC> epcList = new ArrayList<>();
    //    byte[] bytes, epcList2;
    private ImageView fh;
    private TextView title_text;
    private ListView listview;
    private String Status = "";
    private EditText et_num;
    private String nfc = "", rfid;
    private String ids = "", number = "";
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private String locationUpload = "http://" + Ip_Set.IP + "/api/locationUpload";
    private List<String> NFC = new ArrayList<>(), NFCs = new ArrayList<>();
    private List<String> RFIDNumber = new ArrayList<>(), RFIDNumbers = new ArrayList<>();
    private List<String> RFIDId = new ArrayList<>(), RFIDIds = new ArrayList<>();
    private List<String> coding = new ArrayList<>();
    private String taskId = "", id = "", roleId = "", version = "";
    private String url = "http://" + Ip_Set.IP + "/api/taskPointQuery";
    private String urlAbnormal = "http://" + Ip_Set.IP + "/api/exceptionUpload";
    private String urlup = "http://" + Ip_Set.IP + "/api/taskSubmit";
    private String task = "http://" + Ip_Set.IP + "/api/taskPointContentAction";//离线路点内容提交数据（正常/异常）
    private String urlRouteSubmit = "http://" + Ip_Set.IP + "/api/pointSubmit";//整个路点提交
    private String taskTimeOut = "http://" + Ip_Set.IP + "/api/taskTimeOut";//超时处理
    private MyOkHttp myOkHttp;
    private Gson gson;
    private GClient client;
    private List<Site_Bean> data = new ArrayList<>();
    private HandlerThread handlerThread = new HandlerThread("word");
    private Handler handler;
    private volatile boolean isRead = false, isComplete = false;
    private long lastClickTime;
    private String to_be_completed;
    private String status;
    //    private String result;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myOkHttp = new MyOkHttp(getApplicationContext());
        gson = new Gson();
        /*try {
            NfcUtils nfcUtils = new NfcUtils(Site_Activity.this);
        } catch (Exception E) {

        }*/
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper());
    }

    @Override
    public int intiLayout() {
        return R.layout.site_activity;
    }

    @Override
    public void initView() {
        et_num = (EditText) findViewById(R.id.et_num);
        fh = (ImageView) findViewById(R.id.fh);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("");
        listview = (ListView) findViewById(R.id.site_list);
        fh.setOnClickListener(v -> finish());
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                et_num.selectAll();
                if (coding.size() > 0) {
                    if (et_num.getText().toString().trim().equals(coding.get(0))) {
                        for (int i = 0; i < data.size(); i++) {
                            if (et_num.getText().toString().trim().equals(data.get(i).getId())) {
                                Status = data.get(i).getPoint_id();
                                Intent intent1 = new Intent(Site_Activity.this, Site_Data.class);
                                intent1.putExtra("taskPointId", Status);
                                intent1.putExtra("taskId", taskId);
                                startActivity(intent1);
                                break;
                            }
                        }
                    } else {
                        toastShort("编码不匹配！！");
                    }
                }
            }
        });
        /**
         * 点击列表路点
         */
        listview.setOnItemClickListener((parent, view, i, id) -> {
            /* if (version.equals("1")||version.equals("2")){
                 return;
             }*/
            if (i > 0) {
                if (data.get(i - 1).getStatus().equals("未完成")) {
                    toastShort("请按路点顺序巡检");
                    return;
                }
            }
            if (data.get(i).getStatus().equals("异常")) {
                return;
            }
            if (data.get(i).getStatus().equals("正常")) {
                return;
            }
            new BottomMenuFragment(Site_Activity.this)
                    .addMenuItems(new sakura.bottommenulibrary.bottompopfragmentmenu.MenuItem("扫码"))
                    .setOnItemClickListener((menu_item, position) -> {
                        if (position == 0) {
                            ids = data.get(i).getId();//获取判断id
                            startQrCode();
                            Status = data.get(i).getPoint_id();
                        }
                    }).show();


        });
    }

    @Override
    public void initData() {
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id", "");
        roleId = mm.getString("roleid", "");
        version = mm.getString("version", "");
        taskId = getIntent().getStringExtra("taskId");
        load();
    }

    private String offData = "";

    /**
     * 提交离线数据
     */
    private void submitOffData() {
        offData = "off";
        new AlertView(" 提示！", "确定提交部分离线数据", "取消", new String[]{"确定"}, null, Site_Activity.this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                //取消：position=-1,确定 position=0
                if (position == 0) {
                    showDialog(Site_Activity.this);
                    if (Since_case.set().getMapList() != null) {

                        Log.e("超时处理数据", "size" + Since_case.set().getMapList().size());
                        for (int i = 0; i < Since_case.set().getMapList().size(); i++) {
                            Log.e("超时处理数据", "i" + i);
                            upTimeOutData(i);
                        }

                    } else {
                        //异常描述以及视频照片
                        if (Since_case.set().getOffSaveAbnormals() != null) {
                            for (int i = 0; i < Since_case.set().getOffSaveAbnormals().size(); i++) {
                                submitOffAbnormal(i);
                            }
                        } else {
                            getSaveRouteData();
                        }
                    }
                }

                if (position == -1) {
                }
            }
        }).setCancelable(true).setOnDismissListener(Site_Activity.this).show();
    }

    /**
     * 读取
     *
     * @param view
     */
    public void read(View view) {
        ThreadPool.runThread(() -> {
//            if (client == null) {
//                init8188Rfid();
//            }
            //寻卡

                read();

//            useRFID();

        });
    }

    /**
     * 提交
     *
     * @param view
     */
    public void Up_load(View view) {
        Log.d("我要的数据", "要完成的: " + to_be_completed + ", 已经完成的" + completed);
        List<String> list = new ArrayList<>();
//        for (int i = 0; i < data.size(); i++) {
//            if (data.get(i).getStatus().equals("未完成")) {
//                list.add(data.get(i).getStatus());
//                Log.e("路点状态数据", data.get(i).getStatus());
//                if (Since_case.set().getONorOff()) {
//                    toastShort("请完成巡检后再提交");
//                } else {
//                    if (Since_case.set().getOffSaveSiteDate() != null) {
//                        if (Since_case.set().getOffSaveSiteDate().size() > 0) {
//                            submitOffData();
//                        } else {
//                            toastShort("请至少巡检一个路点后再点击提交");
//                        }
//                    } else {
//                        toastShort("请至少巡检一个路点后再点击提交");
//                    }
//
//                }
//                return;
//            }
//        }
//

        if (Since_case.set().getONorOff()) {
            if (Double.valueOf(completed) < Double.valueOf(to_be_completed)) {
                toastShort("暂无达到可提交的进度");
                return;
            }
            new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, Site_Activity.this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        Map<String, String> map = new HashMap<>();
                        map.put("taskId", taskId);
                        //加多一个参数
                        map.put("source", Since_case.set().getSource());
                        HttpOkHttp.getInstance().requestPost(urlup, map, new HttpOkHttp.OkHttpCallBack<String>() {
                            @Override
                            public void requestSuccess(final String s) {
                                Gson gson = new Gson();
                                java.lang.reflect.Type type = new TypeToken<Site_Data_bean>() {
                                }.getType();
                                final Site_Data_bean jsonBean = gson.fromJson(s, type);
                                runOnUiThread(() -> {
                                    if (jsonBean.getState().equals("1")) {
                                        Since_case.set().setUp(true);
                                        finish();
                                        toastShort("上传成功！！");
                                    }
                                });
                                Log.i("datadata", s);
                            }

                            @Override
                            public void requestFailure(String message) {
                                Log.i("datadata", message);
                            }
                        }, String.class);
                    }
                    if (position == -1) {
                    }
                }
            }).setCancelable(true).setOnDismissListener(Site_Activity.this).show();
        } else {
            new AlertView(" 提示！", "是否提交离线数据", "取消", new String[]{"确定"}, null, Site_Activity.this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        showDialog(Site_Activity.this);
                        if (Since_case.set().getMapList() != null) {

                            Log.e("超时处理数据", "size" + Since_case.set().getMapList().size());
                            for (int i = 0; i < Since_case.set().getMapList().size(); i++) {
                                Log.e("超时处理数据", "i" + i);
                                upTimeOutData(i);
                            }

                        } else {
                            //异常描述以及视频照片
                            if (Since_case.set().getOffSaveAbnormals() != null) {
                                for (int i = 0; i < Since_case.set().getOffSaveAbnormals().size(); i++) {
                                    submitOffAbnormal(i);
                                }
                            } else {
                                getSaveRouteData();
                            }
                        }
                    }

                    if (position == -1) {
                    }
                }
            }).setCancelable(true).setOnDismissListener(Site_Activity.this).show();
        }
    }

    private ArrayList<String> mPicList; //上传的图片凭证的数据源
    private File mediaFile;//视频路径
    private File soundFile;//音频路径
    private String taskPointContentId;//路点内容id
    private String remark;//异常描述

    /**
     * 提交离线异常
     *
     * @param j
     */
    private void submitOffAbnormal(final int j) {
        OffSaveAbnormal offSaveAbnormal = Since_case.set().getOffSaveAbnormals().get(j);
        mPicList = offSaveAbnormal.getmPicList();
        ;
        mediaFile = offSaveAbnormal.getMediaFile();
        soundFile = offSaveAbnormal.getSoundFile();
        taskPointContentId = offSaveAbnormal.getTaskPointContentId();
        remark = offSaveAbnormal.getRemark();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        int i = 0;
        for (String path : mPicList) {
            builder.addFormDataPart(taskPointContentId + "-" + i + "upload", taskPointContentId + "-" + i + ".png", RequestBody.create(MediaType.parse(i + "/png"), new File(path)));
            i++;
        }
        if (mediaFile != null) {
            builder.addFormDataPart(taskPointContentId + "mp4", taskPointContentId + "4" + ".mp4",
                    RequestBody.create(MediaType.parse("audio/mpeg"), mediaFile));
        }
        if (soundFile != null) {
            builder.addFormDataPart(taskPointContentId + "mp3", taskPointContentId + "3" + ".mp3",
                    RequestBody.create(MediaType.parse("audio/mpeg"), soundFile));
        }
        builder.addFormDataPart("taskPointContentId", taskPointContentId)
                .addFormDataPart("text", remark)
                .addFormDataPart("source", Since_case.set().getSource());
        Request.Builder request = new Request.Builder().url(urlAbnormal)
                .post(new CmlRequestBody(builder.build()) {
                    @Override
                    public void loading(long current, long total, boolean done) {
                        Log.i("", "current:" + current + ";total:" + total);
                    }
                });
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(1000, TimeUnit.SECONDS)//单位是秒
                .readTimeout(1000, TimeUnit.SECONDS)
                .build();
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("数据", "上传失败 ");
                showToast("上传失败，请检查网络后重试");
                canDialog();
            }

            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful() || response == null || response.body() == null) {
                    //返回值处理
                    showToast("上传失败，请检查网络后重试");
                    canDialog();
                    Log.e("数据", "失败 ");
                } else {
                    if (j == Since_case.set().getOffSaveAbnormals().size() - 1) {//所有的异常视频上传成功
                        Log.e("数据", "上传成功 ");
                        List<OffSaveAbnormal> list = new ArrayList<>();
                        Since_case.set().setOffSaveAbnormals(list);
                        try {
                            Thread.sleep(1000);
                            getSaveRouteData();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        });
    }

    private void load() {
        try {
            if (Since_case.set().getONorOff()) {
                Map<String, String> map = new HashMap<>();
                map.put("taskId", taskId);
                map.put("source", Since_case.set().getSource());
                HttpOkHttp.getInstance().requestPost(url, map, new HttpOkHttp.OkHttpCallBack<String>() {



                    @Override
                    public void requestSuccess(String s) {

                        LogUtils.d("巡检点信息" + s);
                        Bitmap bitmap = null;
                        Gson gson = new Gson();
                        java.lang.reflect.Type type = new TypeToken<SiteActivity_Bean>() {
                        }.getType();
                        SiteActivity_Bean jsonBean = gson.fromJson(s, type);

                        completed = jsonBean.getSchedule();
                        to_be_completed = jsonBean.getRate();
                        Log.d("xxxxx", "to_be_completed: " + to_be_completed);

                        if (jsonBean.getState().equals("1")) {
                            data.clear();
                            NFCs.clear();
                            NFC.clear();
                            RFIDNumbers.clear();
                            RFIDNumber.clear();
                            RFIDIds.clear();
                            RFIDId.clear();
                            coding.clear();
                            for (int i = 0; i < jsonBean.getTaskPoints().size(); i++) {
                                String status = "";
                                if (jsonBean.getTaskPoints().get(i).getStatus().equals("0")) {
                                    status = "未完成";
                                    bitmap = null;
                                    coding.add(jsonBean.getTaskPoints().get(i).getId());
                                    NFC.add(jsonBean.getTaskPoints().get(i).getNfc());
                                    RFIDNumber.add(jsonBean.getTaskPoints().get(i).getNumber());
                                    RFIDId.add(jsonBean.getTaskPoints().get(i).getId());
                                } else if (jsonBean.getTaskPoints().get(i).getStatus().equals("1")) {
                                    status = "正常";
                                    @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.gou);
                                    bitmap = BitmapFactory.decodeStream(is);

                                } else if (jsonBean.getTaskPoints().get(i).getStatus().equals("2")) {
                                    status = "异常";
                                    @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.yi);
                                    bitmap = BitmapFactory.decodeStream(is);
                                }
                                NFCs.add(jsonBean.getTaskPoints().get(i).getNfc());
                                RFIDNumbers.add(jsonBean.getTaskPoints().get(i).getNumber());
                                RFIDIds.add(jsonBean.getTaskPoints().get(i).getId());
                                data.add(new Site_Bean(jsonBean.getTaskPoints().get(i).getPointId(), bitmap, status, jsonBean.getTaskPoints().get(i).getStartdate(), jsonBean.getTaskPoints().get(i).getEnddate(), jsonBean.getTaskPoints().get(i).getTaskPointId(), jsonBean.getTaskPoints().get(i).getId()));
                            }

                            runOnUiThread(() -> {
                                for (int i = 0; i < data.size(); i++) {
                                    Log.e("测试data", "requestSuccess: " + version + data.get(i).getStatus() + getIntent().getStringExtra("state"));
                                    if (!data.get(i).getStatus().equals("异常") && !version.equals("1") && !getIntent().getStringExtra("state").equals("结束")) {
                                        getLocation();
                                        break;
                                    }

                                }

                                Site_Adapter_item siteAdapterItem = new Site_Adapter_item(Site_Activity.this, R.layout.site_item, data);
                                listview.setAdapter(siteAdapterItem);
                                for (int i = 0; i < data.size(); i++) {
                                    if (data.get(i).getStatus().equals("未完成")) {
                                        listview.setSelection(i);
                                        break;
                                    }
                                }
                            });

                        }
                        Log.i("datadata", s);
                    }

                    @Override
                    public void requestFailure(String message) {
                        Log.i("datadata", message);
                    }
                }, String.class);
            } else {
                int position = Since_case.set().getListTaskId().indexOf(taskId);//获取这个路线的id位置
                Since_case.set().setLxPosition(position);
                routeStatusPosition = new ArrayList<>();
                Bitmap bitmap = null;
                SiteActivity_Bean jsonBean = Since_case.set().getSiteActivityBeans().get(position);//从上个页面的数据
                if (jsonBean.getState().equals("1")) {
                    data.clear();
                    NFCs.clear();
                    NFC.clear();
                    RFIDNumbers.clear();
                    RFIDNumber.clear();
                    RFIDIds.clear();
                    RFIDId.clear();
                    coding.clear();
                    for (int i = 0; i < jsonBean.getTaskPoints().size(); i++) {
                        routeStatusPosition.add(jsonBean.getTaskPoints().get(i).getTaskPointId());
                        status = "";
                        if (jsonBean.getTaskPoints().get(i).getStatus().equals("0")) {
                            status = "未完成";
                            bitmap = null;
                            coding.add(jsonBean.getTaskPoints().get(i).getId());
                            NFC.add(jsonBean.getTaskPoints().get(i).getNfc());
                            RFIDNumber.add(jsonBean.getTaskPoints().get(i).getNumber());
                            RFIDId.add(jsonBean.getTaskPoints().get(i).getId());
                        } else if (jsonBean.getTaskPoints().get(i).getStatus().equals("1")) {
                            status = "正常";
                            @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.gou);
                            bitmap = BitmapFactory.decodeStream(is);

                        } else if (jsonBean.getTaskPoints().get(i).getStatus().equals("2")) {
                            status = "异常";
                            @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.yi);
                            bitmap = BitmapFactory.decodeStream(is);
                        } else if (jsonBean.getTaskPoints().get(i).getStatus().equals("3")) {
                            status = "离线完成";
                        }
                        NFCs.add(jsonBean.getTaskPoints().get(i).getNfc());
                        RFIDNumbers.add(jsonBean.getTaskPoints().get(i).getNumber());
                        RFIDIds.add(jsonBean.getTaskPoints().get(i).getId());
                        //Site_Bean(String checking_point, Bitmap asset_img, String status, String place_date, String leave_date, String point_id,String id)
                        data.add(new Site_Bean(jsonBean.getTaskPoints().get(i).getPointId(), bitmap, status, jsonBean.getTaskPoints().get(i).getStartdate(), jsonBean.getTaskPoints().get(i).getEnddate(), jsonBean.getTaskPoints().get(i).getTaskPointId(), jsonBean.getTaskPoints().get(i).getId()));
                    }
                    Since_case.set().setRouteStatusPosition(routeStatusPosition);
                    runOnUiThread(() -> {
                        for (int i = 0; i < data.size(); i++) {
                            if (!data.get(i).getStatus().equals("异常") && !version.equals("1") && !getIntent().getStringExtra("state").equals("结束")) {
                                getLocation();
                                break;
                            }
                        }

                        Site_Adapter_item siteAdapterItem = new Site_Adapter_item(Site_Activity.this, R.layout.site_item, data);
                        listview.setAdapter(siteAdapterItem);
                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).getStatus().equals("未完成")) {
                                listview.setSelection(i);
                                break;
                            }
                        }
                    });

                }
            }
        } catch (NullPointerException e) {
            runOnUiThread(() -> {
                toastShort("请勿胡乱使用NFC！！");
                finish();
            });
        }

    }

    private List<String> routeStatusPosition;

    private void getLocation() {
        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(30000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
    }

    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Site_Activity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Site_Activity.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Site_Activity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Site_Activity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Site_Activity.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Site_Activity.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Site_Activity.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            if (ids.equals(scanResult)) {
                Intent intent = new Intent(Site_Activity.this, Site_Data.class);
                intent.putExtra("taskPointId", Status);
                intent.putExtra("taskId", taskId);
                startActivity(intent);
                // finish();
            } else {
                Toast.makeText(Site_Activity.this, "请按顺序巡检！！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onDismiss(Object o) {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //当该Activity接收到NFC标签时，运行该方法
        //调用工具方法，读取NFC数据
        try {
            nfc = NfcUtils.readNFCId(intent);
            if (NFC.size() > 0) {
                if (nfc.equals(NFC.get(0))) {
                    for (int i = 0; i < NFCs.size(); i++) {
                        if (nfc.equals(NFCs.get(i))) {//通过NFC获取
                            Status = data.get(i).getPoint_id();
                            Intent intent1 = new Intent(Site_Activity.this, Site_Data.class);
                            intent1.putExtra("taskPointId", Status);
                            intent1.putExtra("taskId", taskId);
                            startActivity(intent1);
                            break;
                        }
                    }
                } else {
                    toastShort("NFC不匹配！！");
                }
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //开启前台调度系统
        try {
            NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);
        } catch (Exception e) {
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //关闭前台调度系统 try {
        //
        //        }catch (Exception e){}
        try {
            NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
        } catch (Exception e) {

        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        load();
    }


    @Override
    protected void onDestroy() {
        try {
            mlocationClient.onDestroy();
            stop();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            handler.removeCallbacksAndMessages(null);
            handlerThread.quit();
        }
        super.onDestroy();
    }

    private void locationload(String location) {
        Map<String, String> map = new HashMap<>();
        map.put("location", location);
        map.put("taskId", taskId);
        map.put("source", Since_case.set().getSource());
        HttpOkHttp.getInstance().requestPost(locationUpload, map, new HttpOkHttp.OkHttpCallBack<String>() {
            @Override
            public void requestSuccess(final String s) {

            }

            @Override
            public void requestFailure(String message) {

            }
        }, String.class);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
                locationload(amapLocation.getLongitude() + "," + amapLocation.getLatitude());
                Log.e("测试定位数据", amapLocation.getLongitude() + "," + amapLocation.getLatitude());
                //  Toast.makeText(Site_Activity.this,amapLocation.getLongitude()+","+amapLocation.getLatitude(),Toast.LENGTH_SHORT).show();

            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        } else {
            LogUtils.e("测试数据为空");
        }
    }

    private void upTimeOutData(final int i) {//超时数据优先提交
        Map<String, String> map = new HashMap<>();
        String remark = Since_case.set().getMapList().get(i).get("remark");
        String taskId = Since_case.set().getMapList().get(i).get("taskId");
        map.put("remark", remark);
        map.put("taskId", taskId);
        Log.e("超时处理数据", "upTimeOutData: " + remark + taskId);
        //加多了一个参数
        map.put("source", Since_case.set().getSource());
        myOkHttp.post(taskTimeOut, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("提交失败,请重试");
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException, JSONException {
                String responseData = response.body().string();
                try {
                    Log.e("超时处理数据", responseData);
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getString("state").equals("1")) {
                        if (i == Since_case.set().getMapList().size() - 1) {
                            List<Map<String, String>> mapList = new ArrayList<>();
                            Since_case.set().setMapList(mapList);//提交完清空数据
                            //异常描述以及视频照片
                            if (Since_case.set().getOffSaveAbnormals() != null) {
                                for (int i = 0; i < Since_case.set().getOffSaveAbnormals().size(); i++) {
                                    submitOffAbnormal(i);
                                }
                            } else {
                                getSaveRouteData();
                            }

                        }
                    }
                    if (jsonObject.getString("state").equals("2")) {
                        showToast("提交失败,请重试");
                        canDialog();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static int num, num2;

    private static synchronized void increment() {
        num2++;
    }

    /**
     * 拿到保存的路点内容
     */
    private void getSaveRouteData() {
        num = 0;
        num2 = 0;
        List<OffSaveSiteDate> date = Since_case.set().getOffSaveSiteDate();
        if (date != null) {//避免离线状态没有数据就点击提交
            if (date.size() > 0) {
                for (int i = 0; i < date.size(); i++) {
                    if (date.get(i).getListTaskPointContentId() != null) {
                        if (date.get(i).getListTaskPointContentId().size() > 0) {
                            for (int j = 0; j < date.get(i).getListTaskPointContentId().size(); j++) {
                                submitRouteContentData(date.get(i).getListTaskPointContentId().get(j));
                                num++;
                            }
                        } else {
                            submitRouteData();
                        }
                    }

                }
            } else {
                submit();//只有在线的数据
            }
        } else {
            submit();//只有在线的数据
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("text----","onStart");
        flag=false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("text----","onStop");

        flag=false;
    }

    /**
     * 路点内容提交
     *
     * @param taskPointContentId
     */
    private void submitRouteContentData(String taskPointContentId) {
        Map<String, String> map = new HashMap<>();
        map.put("taskPointContentId", taskPointContentId);
        map.put("source", Since_case.set().getSource());
        myOkHttp.post(task, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("离线任务数据提交失败");
            }

            @Override
            public void requestSuccess(Response response) throws IOException, JSONException {
                String responseData = response.body().string();
                java.lang.reflect.Type type = new TypeToken<Site_Data_bean>() {
                }.getType();
                final Site_Data_bean jsonBean = gson.fromJson(responseData, type);
                increment();
                if (jsonBean.getState().equals("1")) {
                    Log.e("测试数据", num + "GG" + num2);
                    if (num == num2) {//所有路点提交完成
                        showToast("路点内容提交完成");
                        submitRouteData();
                    }
                }
            }
        });
    }

    /**
     * 循环提交路点
     */
    private void submitRouteData() {
        for (int o = 0; o < Since_case.set().getOffSaveSiteDate().size(); o++) {
            Log.e("测试提交数据", String.valueOf(o));
            submitRoute(o);
        }
    }

    private void submitRoute(final int o) {//提交路点
        OffSaveSiteDate offSaveSiteDate = Since_case.set().getOffSaveSiteDate().get(o);
        Map<String, String> map = new HashMap<>();
        map.put("taskPointId", offSaveSiteDate.getTaskPointId());
        map.put("start", offSaveSiteDate.getStateData());
        map.put("end", offSaveSiteDate.getEndData());
        map.put("source", Since_case.set().getSource());
        Log.e("数据", "startDate:" + offSaveSiteDate.getStateData() + "endDate：" + offSaveSiteDate.getEndData());
        myOkHttp.post(urlRouteSubmit, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("离线任务数据提交失败");
            }

            @Override
            public void requestSuccess(Response response) throws IOException, JSONException {
                final String responseData = response.body().string();
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<Site_Data_bean>() {
                }.getType();
                final Site_Data_bean jsonBean = gson.fromJson(responseData, type);
                runOnUiThread(() -> {
                    Log.e("数据", responseData);
                    if (jsonBean.getState().equals("1")) {
                        if (o == Since_case.set().getOffSaveSiteDate().size() - 1) {
                            Log.e("数据", "测试");
                            List<OffSaveSiteDate> dates = new ArrayList<>();
                            Since_case.set().setOffSaveSiteDate(dates);
                            toastShort("路点提交成功");
                            if (!TextUtils.isEmpty(offData)) {
                                if (offData.equals("off")) {
                                    finish();
                                    return;
                                }
                            }
                            submit();
                        }
                    }
                });
            }
        });
    }

    /**
     * 这里应该是整个路线提交
     */
    private void submit() {
        Map<String, String> map = new HashMap<>();
        map.put("taskId", taskId);
        //加多一个参数
        map.put("source", Since_case.set().getSource());
        HttpOkHttp.getInstance().requestPost(urlup, map, new HttpOkHttp.OkHttpCallBack<String>() {
            @Override
            public void requestSuccess(final String s) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<Site_Data_bean>() {
                }.getType();
                final Site_Data_bean jsonBean = gson.fromJson(s, type);
                runOnUiThread(() -> {
                    if (jsonBean.getState().equals("1")) {
                        Since_case.set().setUp(true);
                        canDialog();
                        finish();
                        toastShort("上传成功！！");
                    }
                });
                Log.i("datadata", s);
            }

            @Override
            public void requestFailure(String message) {
                Log.i("datadata", message);
            }
        }, String.class);
    }


    private void showToast(final String msg) {
        runOnUiThread(() -> Toast.makeText(Site_Activity.this, msg, Toast.LENGTH_SHORT).show());
    }

    private ProgressDialog progressDialog;

    /**
     * 数据加载弹窗
     *
     * @param context
     */
    private void showDialog(final Context context) {
        runOnUiThread(() -> {
            progressDialog = new ProgressDialog(context);
            progressDialog.setTitle("数据加载中");
            progressDialog.setMessage("Loading...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        });
    }

    /**
     * 关闭进度圈圈
     */
    private void canDialog() {
        if (progressDialog != null) {
            runOnUiThread(() -> progressDialog.cancel());
        }
    }

    private void init8188Rfid() {
//        client = new GClient();
//        if (client.openCusAndroidSerial("/dev/ttysWK0:115200", 64, 100)) {
//// 订阅标签上报事件
//            client.onTagEpcLog = (readName, logBaseEpcInfo) -> {
//// 回调内部如有阻塞，会影响 API 正常使用
//// 标签回调数量较多，请将标签数据先缓存起来再作业务处理
//                if (null != logBaseEpcInfo && 0 == logBaseEpcInfo.getResult()) {
//                    if (isComplete) {
//                        isComplete = false;
//                        rfid = logBaseEpcInfo.getEpc();
//                        LogUtils.e("读取到的" + rfid);
//                        handler.post(runRFID);
//                            /*handler.removeCallbacks(runRFID);
//                            handler.postDelayed(runRFID, 200);*/
//                    }
//                }
//            };
//// 取消订阅标签上报事件
//            client.onTagEpcOver = (s, logBaseEpcOver) -> LogUtils.d("Epc log over.");
//            setBaseBand();
//        }

//        if (isComplete) {
//            isComplete = false;
//            rfid = logBaseEpcInfo.getEpc();
//            LogUtils.e("读取到的" + rfid);
//            handler.post(runRFID);
                /*handler.removeCallbacks(runRFID);
                handler.postDelayed(runRFID, 200);*/
//        }
        //上报事件
        client = new GClient();
        if (client.openCusAndroidSerial("/dev/ttysWK0:115200", 64, 100)) {
            client.onTagEpcLog = (readName, logBaseEpcInfo) -> {
                if (null != logBaseEpcInfo && logBaseEpcInfo.getResult() == 0) {
                    if (isComplete) {
                        isComplete = false;
                        rfid = logBaseEpcInfo.getEpc();
                        LogUtils.e("读取到的" + rfid);
                        Log.e(TAG, "读取到的" + rfid );
//                        result = logBaseEpcInfo.getEpc();
//                        LogUtils.e("读取到的" + result);
//                        handler.post(runRFID);
                    }
                }
            };

//            client.onTagEpcOver = (s, logBaseEpcOver) -> LogUtils.d("Epc log over.");
//            setBaseBand();
        }

    }

    /**
     * 在这里处理RFID数据
     */
    private Runnable runRFID = () -> {
        stop();
        Log.d("TAG======", "11111111");

        ThreadPool.runThread(() -> {
                Log.d("TAG=======", "222222222");
            if (RFIDNumber.size() > 0) {
                //Log.d(TAG, "RFIDNumber="+ new Gson().toJson(RFIDNumber));
                Log.d("TAG=======", rfid + "," + RFIDNumber.get(0));
                if (rfid.equals(RFIDNumber.get(0))) {
                    Log.d("TAG=======", "444444444444");
                    for (int i = 0; i < RFIDNumbers.size(); i++) {
                        Log.d("TAG=======", "66666666666");
                        if (rfid.equals(RFIDNumbers.get(i))) {
                            Log.d("TAG=======", "7777777777777");
                            Status = data.get(i).getPoint_id();

//                            if (status.equals("已完成") && status.equals("异常")) {
                                Intent intent1 = new Intent(Site_Activity.this, Site_Data.class);
                                intent1.putExtra("taskPointId", Status);
                                intent1.putExtra("taskId", taskId);
                                startActivity(intent1);
                                flag= true;
//                            }
                            break;
                        }/*else {

                            toastShort("未能识别到此巡检点！");
                        }*/
                    }
                    return;
                }
            }
            if (RFIDId.size() > 0) {
                Log.d("TAG=======", "RFIDIds" + RFIDIds);
//                String result = RFIDId.get(i);
//                    if (!rfid.equals(result)) {
//                        toastShort("对不起，该路线中没有该巡检点");
//                    }
                // if (rfid.equals(RFIDId.get(0))) {

                for (int i = 0; i < RFIDIds.size(); i++) {

//

//                        if (!rfid.equals(result)) {
//                            toastShort("该路线没有此巡检点！");
//                        }
                        if (rfid.equals(RFIDIds.get(i))) {
                            Status = data.get(i).getPoint_id();
                            Log.d("你好", "status: " + status + ",Status：" + Status);

//                            if (data..equals("已完成") && status.equals("异常")) {
                                Intent intent1 = new Intent(Site_Activity.this, Site_Data.class);
                                intent1.putExtra("taskPointId", Status);
                                intent1.putExtra("taskId", taskId);
                                startActivity(intent1);
                                flag= true;
//                            }

                            break;
                        }/*else {
//                            //todo 新增提示
                        }*/

                    }
               // }
                /* else {
                    toastShort("请按顺序巡检");
                }*/
            }

        });
    };

    private void continuousRead() {

        UHFService mDevice = UHFService.getInstance();
        if (mDevice.open()) {
            if (mDevice.inventoryStart()) {
                mDevice.setParameters(UHFService.PARAMETER_CLEAR_EPCLIST_WHEN_START_INVENTORY, 0);
                mDevice.setPower(33);
                int i = 0;
                Log.d(TAG, "一直连续读: " + i++);
            }
        }
    }
    /**
     * 读卡功能模块
     */
    private void read() {
        isComplete = true;
 //1 个天线读卡, 读取 EPC 数据区以及 TID 数据区
//        MsgBaseInventoryEpc msgBaseInventoryEpc = new MsgBaseInventoryEpc();
//        msgBaseInventoryEpc.setAntennaEnable(EnumG.AntennaNo_1);
//        //msgBaseInventoryEpc.setInventoryMode(EnumG.InventoryMode_Inventory);无限轮询
//        msgBaseInventoryEpc.setInventoryMode(0);//只读取一遍
//        ParamEpcReadTid tid = new ParamEpcReadTid();
//        tid.setMode(EnumG.ParamTidMode_Auto);
//        tid.setLen(6);
//        msgBaseInventoryEpc.setReadTid(tid);
//        client.sendSynMsg(msgBaseInventoryEpc);
//        //getRtCode消息返回码
//        if (0 == msgBaseInventoryEpc.getRtCode()) {
//            isRead = true;
//            LogUtils.d("Inventory epc successful.");
//        } else {
//            LogUtils.d("Inventory epc error.");
//        }
        MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.scan);
        UHFService mDevice = UHFService.getInstance();

        if (mDevice.open()) {
            Log.d(TAG, "开始寻卡");
            //连续寻卡
            if (mDevice.inventoryStart()) {
                Log.d(TAG, "开始连续寻卡");
                mDevice.setParameters(UHFService.PARAMETER_CLEAR_EPCLIST_WHEN_START_INVENTORY, 0);
                mDevice.setPower(2);

                //一共寻到的卡的总数
                int num = mDevice.getTagIDCount();
                if (num == 0) {
                    Log.d(TAG, "list为空");
                } else {

                    //寻到卡的ID
                    epcList = mDevice.getTagIDs();
                    Log.d(TAG, epcList + "。。。");
                    for (int i = 0; i < epcList.size(); i++) {
//                        epcList.clear();
                        Log.d(TAG, epcList.get(i).getId());
//                            Log.d("hhhhhhhhhhhTID: ", epcList2.toString());
                        Log.d(TAG, num+"");
                        Log.d(TAG, "________________________");

                        rfid = epcList.get(i).getId();

                        try {
                            if (rfid != null && !"".equals(rfid)) {
                                rfid = rfid.substring(0, 16);
                                VibrateUtils.getInstance(Site_Activity.this).vibrate(100);
                                mediaPlayer.start();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }


                        Log.d("TAG=======", rfid);

                        //如果列表里面有数据就停止读取
                        if (rfid!=null) {
                            stop();
//                            break;
                        }

                    }

                    handler.removeCallbacks(runRFID);
                    handler.post(runRFID);

//                    Log.d(TAG, rfid);

                    isRead = true;
                    LogUtils.d("Inventory epc successful.");
                }
                mediaPlayer.release();
                VibrateUtils.getInstance(Site_Activity.this).cancel();
                epcList.clear();
//                    mDevice.inventoryStop(); //寻卡结束
//                Log.d(TAG, rfid);
//                toastShort("附近没有巡检点！");
                Log.d(TAG, "寻卡结束");
                Log.d(TAG, "________________________________________");

            }
            else {
                LogUtils.d("Inventory epc error.");
                Log.d(TAG, "连续寻卡失败");
                Toast.makeText(Site_Activity.this, "连续寻卡失败", Toast.LENGTH_SHORT).show();
            }
        }
        else {
            Log.d(TAG, "UHF接口打开失败");
            Toast.makeText(Site_Activity.this, "UHF接口打开失败", Toast.LENGTH_SHORT).show();
        }

    }



    private void stop() {
        // 停止指令，空闲态
//        if (isRead) {
//            MsgBaseStop msgBaseStop = new MsgBaseStop();
//            client.sendSynMsg(msgBaseStop);
//            if (0 == msgBaseStop.getRtCode()) {
//                isRead = false;
//                LogUtils.d("Stop successful.");
//            } else {
//                LogUtils.d("Stop error.");
//            }
//        }

        //错误！！没有初始化
        if (isRead) {
            mDevice.inventoryStop(); //寻卡结束
        }

    }

    //设置功率的方法

    private void setPower() {
        // 功率配置, 将 1 个天线功率设置为 30dBm.
        MsgBaseSetPower msgBaseSetPower = new MsgBaseSetPower();
        Hashtable<Integer, Integer> hashtable = new Hashtable<>();
        hashtable.put(1, 30);
        msgBaseSetPower.setDicPower(hashtable);
        client.sendSynMsg(msgBaseSetPower);
        if (0 == msgBaseSetPower.getRtCode()) {
            LogUtils.d("Power configuration succ essful.");
        } else {
            LogUtils.d("Power configuration error.");
        }
    }
    // TODO: 2023/3/3 暂时用不到

    private void setBaseBand() {
        MsgBaseSetBaseband msgBaseSetBaseband = new MsgBaseSetBaseband();
        /*msgBaseSetBaseband.setqValue(0);//设置单标签读取
        msgBaseSetBaseband.setSession(1);*/
        msgBaseSetBaseband.setqValue(3);//设置多标签读取
        msgBaseSetBaseband.setSession(4);
        client.sendSynMsg(msgBaseSetBaseband);
    }

    /*private void useRFID() {
        try {
            UHFService mDevice = UHFService.getInstance();
            if (mDevice.open()) {
                Log.d(TAG, "开始寻卡");
                if (mDevice.inventoryStart()) {
                    Log.d(TAG, "开始连续寻卡");
                    mDevice.setParameters(UHFService.PARAMETER_CLEAR_EPCLIST_WHEN_START_INVENTORY, 1);
//                    int power = mDevice.getPower();
//                    Log.d(TAG, "power: " + power);
                    mDevice.setPower(30);
//                    String area = mDevice.getRegion();
//                    Log.d(TAG, "area: " + area);
//                    mDevice.setRegion("China2");
                    int num = mDevice.getTagIDCount();
//                    mDevice.readTagData(bytes, null, 2, 2, 4, epcList2);
                    if (num == 0) {
                        Log.d(TAG, "list为空");
                    }
                    else {
                        epcList = mDevice.getTagIDs();
                        for (int i = 0; i < epcList.size(); i++) {
                            Log.d(TAG, epcList.get(i).getId());
//                            Log.d("hhhhhhhhhhhTID: ", epcList2.toString());
                            Log.d(TAG, num+"");
                            Log.d(TAG, "________________________");
                        }
                    }
//                    mDevice.inventoryStop(); //寻卡结束
                    Log.d(TAG, "寻卡结束");
                    Log.d(TAG, "________________________________________");

                }
                else {
                    Log.d(TAG, "连续寻卡失败");
                    Toast.makeText(Site_Activity.this, "连续寻卡失败", Toast.LENGTH_SHORT).show();
                }
            }
            else {
                Log.d(TAG, "UHF接口打开失败");
                Toast.makeText(Site_Activity.this, "UHF接口打开失败", Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            Log.d("error: ", e.toString());
        }
    }*/

    /**
     * 连续点击过多要等300毫秒才能相应下次事件
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    public boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime = time;
        return timeD <= 200;
    }




    private boolean flag=false;
    /**
     * 监听外置按钮事件
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("onKeyDown=====","keyCode="+keyCode+",event="+event.getAction());

        if (keyCode == 142) {

            if (!flag){
                read();
            }

        }
        return super.onKeyDown(keyCode, event);

    }




}
